package com.crm.web.controller;

import com.crm.entity.Right;
import com.crm.entity.Role;
import com.crm.service.IRoleService;
import com.crm.shiro.MyShiroRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Resource
    IRoleService roleService;

    @GetMapping("/json")
    @ResponseBody
    public List<Role> role() {
        return roleService.findAllRoles();
    }

    @RequestMapping("/list")
    public String list(@RequestParam(required = false, defaultValue = "") String roleName,
                       @RequestParam(required = false, defaultValue = "1") Integer pageIndex,
                       Model model) {
        Sort sort = new Sort(Sort.Direction.ASC, "roleId");
        Pageable pageable = PageRequest.of(pageIndex - 1, 3, sort);
        Page<Role> rolePage = roleService.findRole(roleName, pageable);
        model.addAttribute("rolePage", rolePage);
        model.addAttribute("roleName", roleName);//保存查询条件
        return "role/list";
    }

    @RequestMapping("/add")
    public String add(Model model) {
        // 查找所有权限，用于指派授权
        List<Right> rights = roleService.findAllRights();
        model.addAttribute("rights", rights);
        return "role/add";
    }

    @RequestMapping("/edit")
    public String edit(Integer roleId, Model model) {
        Role role = roleService.getRole(roleId);
        model.addAttribute("role", role);
        // 查找角色权限
        List<Right> roleRights = roleService.findRightsByRole(role);
        model.addAttribute("roleRights", roleRights);
        // 查找所有权限，用于指派权限
        List<Right> rights = roleService.findAllRights();
        model.addAttribute("rights", rights);
        return "role/edit";
    }

    @RequestMapping("/save")
    public String save(Role role, String[] rightCodes) {
        if (rightCodes != null) {
            for (String rightCode : rightCodes) {
                Right right = new Right();
                right.setRightCode(rightCode);
                role.getRights().add(right);//将关联的权限添加到角色中，用于级联新增关联表的数据
            }
        }
        roleService.saveRole(role);//新增，会级联新增关联表的数据
        //清空权限缓存
        RealmSecurityManager rsm=(RealmSecurityManager) SecurityUtils.getSecurityManager();
        MyShiroRealm realm=(MyShiroRealm)rsm.getRealms().iterator().next();
        realm.clearCachedAuthorizationInfo();
        return "redirect:/role/list";//增删改之后跳转最好使用重定向
    }

    @RequestMapping("/del/{roleId}")
    @ResponseBody
    public Map del(@PathVariable Integer roleId) {
        Map<String,String> map = new HashMap();
        try {
            roleService.deleteRoleById(roleId);
            map.put("delResult", "true");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("delResult", "false");
        }
        return map;
    }
}
